package com.itzmn.newcode.offer1;

/**
 * @Author: 张梦楠
 * @Date: 2018/12/19 14:10
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description: 合并两个排序列表
 *
 * 输入两个单调递增的链表，输出两个链表合成后的链表，当然我们需要合成后的链表满足单调不减规则。
 *
 * 两个单调递增，合并递增，比较两个链表的值，谁小谁放在前面
 *
 *
 */
public class _16_CombineTwoSortedLinkedLists {

    public static void main(String[] args) {

        new _16_CombineTwoSortedLinkedLists().test();
    }

    private void test() {

        ListNode listNode = initListNode();
        ListNode listNode1 = initListNode();

        Merge(listNode1,listNode);

    }
    public ListNode Merge(ListNode list1,ListNode list2) {

        if (list1 == null && list2 == null){
            return null;
        }

        ListNode head = new ListNode(0);
        ListNode tempHead = head;
        while (list1!=null && list2!= null){

            if (list1.val <= list2.val){
                ListNode temp = list1;
                list1 = list1.next;
                tempHead.next = temp;
                tempHead = temp;
            }else {
                ListNode temp = list2;
                list2 = list2.next;

                tempHead.next = temp;
                tempHead = temp;
            }
        }

        while (list1 != null){
            tempHead.next = list1;
            tempHead = list1;
            list1 = list1.next;
        }
        while (list2 != null){
            tempHead.next = list2;
            tempHead = list2;
            list2 = list2.next;
        }

        logLinkedList(head.next);
        return head.next;


    }

    private void logLinkedList(ListNode head){
        while (head!=null){
            System.out.print(head.val+" ");
            head = head.next;
        }
        System.out.println();
    }
    /**
     * 初始化链表
     * @return
     */
    public ListNode initListNode(){

        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        return listNode1;
    }

    public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }


}
